/**
 * JavaScript document for Blog SAEF module
 * 
 * @package PyroCMS
 * @subpackage Blog SAEF Module
 * @category Modules
 * @dependencies jquery.js 
 * @author Rick Holmes
 */      
var SAEF = (function($){
	var MODULE_URI = SITE_URL + 'addons/default/modules/saef/',
		PYRO_JS_URI = SITE_URL + 'system/cms/themes/pyrocms/js/',
		saef_css = ['css/saef.css'],
		saef_js = ['js/jquery.form.min.js'],
		t, instance,
		wrapper_div,
		editable = false;
	// end var
	
	// loads assets needed by the front-side widget	
	function loadAssets() {
		var i, max;
		// load the ckeditor js from the pyro theme, each load has callback to load the next to avoid js errors
		SAEF.Loader.loadByTag(PYRO_JS_URI + 'ckeditor/ckeditor.js', loadCkeditorAdapter);
				
		// load the saef css
		for (i=0, max=saef_css.length; i < max; i += 1) {
			SAEF.Loader.loadByTag(MODULE_URI + saef_css[i]);
		}
		
		// load the saef js
		for (i=0, max=saef_js.length; i < max; i += 1) {
			if (saef_js[i].indexOf('form') !== -1) {
				SAEF.Loader.loadByTag(MODULE_URI + saef_js[i], bindFormJs);
			} else {
				SAEF.Loader.loadByTag(MODULE_URI + saef_js[i]);
			}			
		}
	}
	
	function loadCkeditorAdapter() {
		SAEF.Loader.loadByTag(PYRO_JS_URI + 'ckeditor/adapters/jquery.js', ckeditorInit);
	}
	
	function update_instance() {
		if (typeof CKEDITOR !== 'undefined') {
			instance = CKEDITOR.currentInstance;
		}		
	}
	
	// initiate ckeditor, called as callback when last ckeditor file is loaded
	function ckeditorInit() {
		if (typeof CKEDITOR !== 'undefined') { // just in case
			clearTimeout(t);
			$('textarea.wysiwyg-simple').ckeditor({
				toolbar: [
					['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink']
				],
				width: '99%',
				height: 100,
				dialog_backgroundCoverColor: '#000',
				defaultLanguage: 'en',
				language: 'en'
			});
			$('textarea.wysiwyg-advanced').ckeditor({
				toolbar: [
					['Maximize'],
					['Cut','Copy','Paste','PasteFromWord'],
					['Undo','Redo','-','Find','Replace'],
					['Link','Unlink'],
					['Table','HorizontalRule','SpecialChar'],
					['Bold','Italic','StrikeThrough'],
					['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl'],
					['Format', 'FontSize', 'Subscript','Superscript', 'NumberedList','BulletedList','Outdent','Indent','Blockquote'],
					['ShowBlocks', 'RemoveFormat', 'Source']
				],
				extraPlugins: 'pyroimages,pyrofiles',
				width: '99%',
				height: 400,
				dialog_backgroundCoverColor: '#000',
				removePlugins: 'elementspath',
				defaultLanguage: 'en',
				language: 'en'
			});
		} else {
			t = setTimeout(ckeditorInit, 100);	
		}			
	}
	
	// bind widget submit even to Ajax handler, uses "ajaxForm" from jquery.form plugin
	function bindFormJs() {
		var options = {
			success: function(retval) { 
				// clear any old alert message and class
				$('#saef-message').removeClass('error').removeClass('warning').removeClass('success').empty();
				// change the look of the user message
				if (retval.indexOf('Error') !== -1) {
					retval = retval.replace('Error: ', '');
					$('#saef-message').addClass('error');
				} else if (retval.indexOf('Success') !== -1) {
					clearForm();
					retval = retval.replace('Success: ', '');
					$('#saef-message').addClass('success');
				} else if (retval.indexOf('Warning') !== -1) {
					retval = retval.replace('Warning: ', '');
					$('#saef-message').addClass('warning');
				}
				$('#saef-message').append(retval).fadeIn('fast');	
			}
		};		
		$('#saef-form').ajaxForm(options);
	}
	
	// clear the form, called only on success
	function clearForm() {
		var i;
		// CKEDITOR		
		for (i in CKEDITOR.instances) {
			if (CKEDITOR.hasOwnProperty('instances')) {	
				CKEDITOR.instances[i].setData('');
			}
		}			
		// the rest
		$('#title').val('');
		$('#category').val('');
	}

	/* ----------------------------------------------------------
		Below is the code to allow editing of posts.
		This may be added to your main js file if you want to allow 
		editing on pages that do not have the SAEF form.
		You will also need the ckeditorInit() function above,
		plus ckeditor/ckeditor.js and ckeditor/adapters/jquery.js
		from the Pyro theme directory.
	----------------------------------------------------------- */

	// the master function that enables and starts editability
	function editInit() {
		// check the settings to see if editing is enabled and get the wrapper div
		$.ajax({
			url: BASE_URI + 'saef/get_settings',
			type: 'post',
			success: function(retval) {
				if (retval !== 'false') { // if editable, check for div and go
					editable = true;
					wrapper_div = retval;
					checkWrap(retval);	
				}
			}
		});
	}

	// check to see if wrapper div exists, check for author logon
	function checkWrap(wrapper_div) { 
		var slug;
		if ($('.'+wrapper_div).length > 0) {
			slug = window.location.pathname.split('/').pop(); 
			check_author_login(slug);
			bindEditLinks(slug);
		}
	}
	
	// check to see whether the author of the post is logged in
	function check_author_login(slug) {
		$.ajax({
			url: BASE_URI + 'saef/check_author_login',
			data: 'slug=' + slug,
			type: 'post',
			success: function(retval) {
				if (retval === 'ok') {
					addEditLink('intro');
					addEditLink('body');
				}
			}
		});
	}
	
	// add an edit link
	function addEditLink(type) {
		var html = '<a id="' + type + '-edit" class="inline-edit-link" href="#">Edit</a>';
		$('.post_'+type).append(html);
	}
	
	// edit link functionality
	function bindEditLinks(slug) {
		$('a.inline-edit-link').live('click', function(){
			var par = $(this).parent(),
				id = $(this).attr('id'),
				divType = id.slice(0, -5),
				content, newContent, form, alert, timr;
			
			$(par).children('a.inline-edit-link').remove(); // otherwise will be in editor
			content = $(par).html();
			form = '<form id="saef-' + id + '" method="post" action="' + SITE_URL + 'saef/edit/' + divType + '"><textarea class="wysiwyg-simple" name="content">' + content + '</textarea><input type="hidden" name="slug" value="' + slug + '" /><button type="submit" class="btn blue">Submit</button></form>';
			$(par).html(form);
			ckeditorInit();
			$('#saef-'+id).ajaxForm({
				beforeSubmit: function(arr, form, options) {
					newContent = arr[0]['value'];
				},
				success: function(retval) {
					if (retval === 'ok') {
						alert = '<div class="alert success"><p>The post has been updated!</p></div>';
						$(par).prepend(alert);
						timr = setTimeout(function(){
								$('.alert').fadeOut('slow', function(){
									$(par).children('div.alert').remove();
									clearTimeout(timr);
									$(par).html(newContent);
									addEditLink(divType);
								});
						}, 1000);
					} else {
						alert = '<div class="alert error"><p>Sorry, your changes could not be made.</p></div>';
						$(par).prepend(alert);
						timr = setTimeout(function(){
							$('.alert').fadeOut('slow', function(){
								$(par).children('div.alert').remove();
								clearTimeout(timr);
								$(par).html(content);
								addEditLink(divType);
							});
						}, 1000);
					}
				}
			});
			
			return false;
		});
	}

	/* end edit code */
		
	return {
		init: function() {
			loadAssets();
			
			editInit();
		}	
	};
	
}(jQuery));


// loader that may be called anywhere
SAEF.Loader = (function(APP, $){
	var parent = SAEF;
	
	// add <link> or <script> tag to <head>
	function loadByTag(file, callback) { 
		var p = file.lastIndexOf('.'),
			ext = file.slice(p + 1),
			head = document.getElementsByTagName('head')[0],
			link,
			script,
			parts;
			
		switch (ext) {
		case 'js':
			script = document.createElement('script');
			
			// run callback if applicable
			script.onreadystatechange = function() {
				if (script.readyState === 'loaded' || script.readyState === 'complete') { // for IE
					script.readystatechange = null;
					if (callback) {
						callback();
					}
				}
			};
			script.onload = function() { // everybody else
				if (callback) {
					callback();
				}				
			};
			
			script.src = file;
			head.appendChild(script);			
			break;
		case 'css':
			link = document.createElement('link');
			link.href = file;
			link.rel = 'stylesheet';
			head.appendChild(link);	
			break;
		}	
	}
	
	// load by Ajax
	function loadByXHR(filepath, callback) {
		if (filepath.indexOf('.js') === -1) {
			return;
		}		
		$.getScript(filepath, function(){
         if (callback) {
				callback();
			}
     });
	}
	
	// reveals
	return {
		loadByTag : loadByTag,
		loadByXHR : loadByXHR	
	};
}(SAEF, jQuery));

// load the js only if jQuery is available, cause you never know
var timout;
(function loadJS() {
	if (window.jQuery) {
		clearTimeout(timout);
		$(document).ready(function() { 
			SAEF.init();
		});
	} else {
		timout = setTimeout(loadJS, 250);	
	}
}());
